﻿using System;
using System.Linq;
using Mondial2014.Models.Context;
using Mondial2014.Models.Monitoring;
using Mondial2014.Utils.Events;

namespace Mondial2014.Utils
{
    public static class UpdatesListener
    {
        [EventDispatcher.Subscribe]
        public static void OnMatchUpdatedEvent(MatchUpdatedEvent matchUpdatedEvent)
        {
            using (var context = new Mondial2014DbContext())
            {
                context.Updates.Add(new FixtureResultUpdate
                {
                    Date = DateTime.Now,
                    Fixture = context.Fixtures.Single(f => f.Id == matchUpdatedEvent.FixtureId)
                });
                context.SaveChanges();
            }
        }

        [EventDispatcher.Subscribe]
        public static void OnKnockoutsStageUpdated(KnockoutsStageUpdatedEvent knockoutsStageUpdated)
        {
            using (var context = new Mondial2014DbContext())
            {
                context.Updates.Add(new KnockoutUpdate
                {
                    Date = DateTime.Now,
                    Team = context.Teams.Single(t => t.Id == knockoutsStageUpdated.TeamId),
                    Stage = context.Stages.Single(s => s.Level == (int)knockoutsStageUpdated.StageType)
                });
                context.SaveChanges();
            }
        }

        [EventDispatcher.Subscribe]
        public static void OnScoresUpdatedEvent(ScoresUpdatedEvent scoresUpdatedEvent)
        {
            using (var context = new Mondial2014DbContext())
            {
                var position = 0;
                var score = -1;
                foreach (var gambler in context.Gamblers.ToArray().OrderByDescending(g => g.TotalScore))
                {
                    gambler.LastPosition = gambler.CurrentPosition;
                    if (score != gambler.TotalScore)
                    {
                        position++;
                        score = gambler.TotalScore;
                    }
                    gambler.CurrentPosition = position;
                }
                context.SaveChanges();
            }
        }
    }
}